<?php

namespace StudyBuddy;

class Responder {
    const PAGE_OPEN = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="/style/1/www/_main.css">
</head>
<body>';

    const PAGE_CLOSE = '</body></html>';

    const JS_OPEN = '<script type="text/javascript">';

    const JS_CLOSE = '</script>';

    const CSS_OPEN = '<style type="text/css">';

    const CSS_CLOSE = '</style>';


    /**
     * Flag indicates that
     * request came to the iframe
     * This usually happends when form
     * is submitted via hijaxForm javascript
     * The puprose of this flag is to allow
     * the sending of response json to be sent
     * out via sendJSON in a special way
     *
     * @see sendJSON()
     *
     *
     * @var bool
     */
    protected static $bIframe = false;

    /**
     * Send the string to a browser and exit
     *
     * @param array $arrJSON
     * @param int httpCode default is 200
     * @param array $headers
     * @param boolean $addJSTags if true, then
     * string will be sent as an HTML page that contains
     * javascript
     * Javascript will pass the json object to
     * the parent window's function fParseResponse
     * but only if parent object exists and contains
     * fParseQfJson script
     */
    public static function sendJSON(array $aJSON, array $headers = null, $httpCode = 200, $addJSTags = false) {

        if (Request::isIframe() || !empty($addJSTags)) {
            self::sendJsonPage($aJSON);
            exit;
        }

        $contentType = "Content-Type: text/json; charset=UTF-8";
        $res = json_encode($aJSON);

        d('Sending json: ' . $res);
        header("HTTP/1.1 " . $httpCode . " OK");
        header($contentType);
        echo($res);
        fastcgi_finish_request();
        exit;
    }

    /**
     * Send out response to JSONP Request
     * by sending out application/javascript Content-Type header
     * and then string: callbackfunction with
     * JSON-encoded data as callback's argument
     * and then calling fastcgi_finish_request();
     * and exit;
     *
     * @param array $aJSON
     * @param string $callback
     * @throws \InvalidArgumentException
     */
    public static function sendJSONP(array $aJSON, $callback) {
        if (!is_string($callback)) {
            throw new \InvalidArgumentException('$callback must be a string. Was: ' . gettype($callback));
        }

        header("HTTP/1.1 200 OK");
        header("Content-Type: application/javascript; charset=UTF-8");

        echo $callback . '(' . json_encode($aJSON) . ')';
        fastcgi_finish_request();
        exit;
    }

    /**
     * Outputs html page
     * that includes ONLY javascript
     * that contains json encoded array or data
     *
     * @param string $aJson
     * @return
     */
    public static function sendJsonPage(array $aJson) {
        $strHeader = "Content-Type: text/html";
        $json = json_encode($aJson);

        $strResult = self::PAGE_OPEN . self::JS_OPEN . '
        //alert("Dude!");
		if(parent && parent.oSL && (parent.oSL.oFrm && parent.oSL.oFrm.fParseResponce) ){
		parent.oSL.oFrm.fParseResponce(' . $json . ');
		}
        else{
			alert("parent page does not have required oSL.oFrm.fParseResponce");
        }
		' . self::JS_CLOSE . self::PAGE_CLOSE;

        header($strHeader);

        echo $strResult;
        fastcgi_finish_request();
        exit;
    }

    /**
     * Generates a simple
     * html page with contents of
     * an error message inside a special
     * <div>
     *
     * @param string $sError
     * @return string Error message to put inside
     * the page
     */
    public static function makeErrorPage($sError) {
        return self::PAGE_OPEN . "\n" . '<div id="excsl"><div id="tools">' . $sError . '</div></div>' . "\n" . self::PAGE_CLOSE;
    }

    /**
     * Redirecting browser to a new url
     * using the header "Location" value
     *
     * @param string $url url where to redirect. Default is '/' meaning to www root
     */
    public static function redirectToPage($url = null) {

        if (null === $url) {
            $url = ( empty($_SERVER['HTTP_REFERER'])) ? '/' : $_SERVER['HTTP_REFERER'];
        }

        if (Request::isAjax()) {
            self::sendJSON(array('redirect' => $url));
        }

        header("Location: " . $url);
        fastcgi_finish_request();
        exit(0);
    }

    /**
     * Make a url from values in
     * $_SESSION['LOCATION'] array
     *
     * @return string a assembled url
     */
    public static function makeUrlFromLocation() {
        $sUrl = null;
        if (isset($_SESSION) &&
                !empty($_SESSION['LOCATION']) &&
                !empty($_SESSION['LOCATION']['H']) &&
                !empty($_SESSION['LOCATION']['a'])) {
            $sUrl = self::makeUri('', array_merge($_SESSION['LOCATION']['H'], array('a' => $_SESSION['LOCATION']['a'])));
        }

        return $sUrl;
    }

}
